package com.cx.bank.util;

import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.util.concurrent.TimeUnit;

/**
 * @author jxau_scf
 * @date 2021/7/27 - 16:53
 */
public class RedisLock {
    private static final String LOCK_SUCCESS = "OK";
    private static final String LOCK_VALUE = "lock";
    private static final int EXPIRE_SCONDS = 3;
    RedisCommands<String, String> syncCommands;

    public boolean lock(String userId){
        String redisKey = this.formatRedisKey(userId);

        RedisClient redisClient = RedisClient.create("redis://@120.78.76.182:6379/0");
        StatefulRedisConnection<String, String> connect = redisClient.connect();syncCommands = connect.sync();
        syncCommands.setnx(redisKey,LOCK_VALUE);
        String ok = syncCommands.setex(redisKey, EXPIRE_SCONDS, LOCK_VALUE);

//        syncCommands.set(redisKey,LOCK_VALUE, "NX","EX", EXPIRE_SCONDS);
        return LOCK_SUCCESS.equals(ok);


    }

    public void unlock(String userId){
        String redisKey = this.formatRedisKey(userId);
        syncCommands.del(redisKey);
    }

    private String formatRedisKey(String userId) {
        return "keyPrefix:"+userId;
    }
}
